#include "configmanager.h"
#include "defectstatistics.h"
#include "errordialogmanager.h"

#include <QDateTime>
#include <QDir>
#include <QFile>

// DefectStatistics::DefectStatistics() {}

void DefectStatistics::exportDataToCSV(const QVector<QVector<int>> &data)
{
    int goodLabelsCount = 0;
    int defectLabelsCount = 0;
    QMap<QString, int> defectCounts;

    // 遍历数据，统计各个缺陷的数量
    for (const auto& defects : data) {
        if (defects.isEmpty()) {
            ++goodLabelsCount;
        } else {
            ++defectLabelsCount;
            for (int defect : defects) {
                std::vector<int> vec;
                vec.push_back(defect);
                QString key = NGTable::getInstance().parseNGListToDescription(vec);
                if (!defectCounts.contains(key)) {
                    defectCounts[key] = 0;
                }
                defectCounts[key] += 1;
            }
        }
    }

    // 打开CSV文件准备写入
    //QFile file("master/output.csv");
    QDir dir(upanPath);
    if (!dir.exists()) {
        LogError << "upanPath is not exit :" << upanPath;
        ErrorDialogManager::instance().showNonBlockingError("导出总结失败","无法检测到U盘");
        return ;
    }
    QFile file(upanPath + ConfigManager::getInstance().ccnfigfileName() + ".csv");

    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&file);

        // 设置编码为 UTF-8 以支持中文
        out.setCodec("UTF-8");

        // 封装中文并写入统计数据
        QString labelHeader = "标签,数量\n";
        QString goodLabelText = "良品标签,";
        QString defectLabelText = "缺陷标签,";

        QString exportTime = "导出时间: " + QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss") + "\n";
        QString currentLabel = "当前标签编号: " + ConfigManager::getInstance().ccnfigfileName() + "\n";
        out << currentLabel;
        out << exportTime;
        out << "\n";
        out << "\n";
        out << labelHeader;
        out << goodLabelText << goodLabelsCount << "\n";
        out << defectLabelText << defectLabelsCount << "\n";
        out << "\n";
        QString defectTypeLabel = "缺陷类型: ";
        for (auto it = defectCounts.begin(); it != defectCounts.end(); ++it) {
            QString defectLine = defectTypeLabel + it.key() + "," + QString::number(it.value()) + "\n";
            out << defectLine;
        }

        // 分隔符行
        QString detailHeader = "\n详情:\n缺陷描述\n";
        out << detailHeader;

        // 写入每一项的具体数据，带自增ID号
        int id = 1;
        for (const QVector<int>& item : data) {
            std::vector<int> stdVec = item.toStdVector();
            QString detail;

            if (stdVec.empty()) {
                detail = "良品";
            } else {
                detail = NGTable::getInstance().parseNGListToDescription(stdVec);
            }

            QString idLine = QString::number(id++) + ":\t\t" + detail + "\n";
            out << idLine;
        }

        file.close();
        ErrorDialogManager::instance().showNonBlockingInfo("导出总结成功","文件名:"+ConfigManager::getInstance().ccnfigfileName() + ".csv");
        qInfo() << "CSV file has been generated successfully.";
    } else {
        ErrorDialogManager::instance().showNonBlockingError("导出总结失败","无法创建U盘文件");
        return ;
        qCritical() << "Failed to open file for writing.";
    }
}
